'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
// const Logger = require('egg-logger').Logger;
// const FileTransport = require('egg-logger').FileTransport;
// const ConsoleTransport = require('egg-logger').ConsoleTransport;

// 定义创建接口的请求参数规则
const createRule = {
  accesstoken: 'string',
  title: 'string',
  tab: { type: 'enum', values: [ 'ask', 'share', 'job' ], required: false },
  content: 'string',
};
class HomeController extends Controller {
  async index() {
    this.ctx.body = 'hi, egg88999';//用于测试HTTP
  }

async testToken(){
  const {ctx} = this;
  const list  =await ctx.model.Token.findAll();
  console.log(list)
    ctx.body={list:list};

}

async testSer(){
  const {ctx,service} = this;
 
    await  service.isService.isCanSign(2)
  // const one  =await ctx.model.CanNotSign.findOne();
  console.log("测试不能")

    ctx.body='ok';

}

  //修改
  async update() {
    const _ctx = this.ctx;
    console.log("修改");
    let para = {
      username: "test名"
    };
    const user = await _ctx.model.User.update(para, {
      where: {
        userid: "13"
      }
    });
    _ctx.body = "ok";
  }

async testCache(){
  const {ctx} =this;
  const logger = ctx.app.loggers;
 
  logger.log.debug('这是调试')
  logger.log.info('这是信息')
  logger.log.error('这是错误的')
 
  const isSigin = await ctx.model.WithdrawHistory.find({
    where:{
      userId:1
    }
  })
  ctx.body = {data:isSigin};
}

 




  
  async testPromise(ctx){
    //[{"key":"Content-Type","value":"application/x-www-form-urlencoded","description":""}]
    const tt=ctx.request.body; 
    console.log('tt=',tt)
     await this.service.topics.promise(tt.test).then(function(data){
      // console.log("ok>>>>>"+data)     
      const res = { test: "成功的promise", code: 200 }  
       ctx.body = res ;
    },function(err){
      const res = { warn: err, code: 400 }  
       ctx.body = res  ;
    }).catch(function(e){console.log(e)})
}

async web(){
  const ctx =this.ctx
  console.log(this.ctx.app.config.wechat_config)
  ctx.body=`<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" />
  file: <input name="file" type="file" />
  <button type="submit">upload</button>
</form>`
}
  async jwtTest() { 
    const ctx = this.ctx;    

      const authorization = ctx.get('Authorization');
      console.log(authorization)
      if (authorization === '') {
          ctx.throw(401, 'no token detected in http header "Authorization"');
          return
      }
      // const token = authorization.split('.')[1];
      //  console.log(token)
      let tokenContent;
      // tokenContent = await jwt.verify(authorization, 'A');     //如果token过期或验证失败，将抛出错误
      //     console.log(tokenContent)
      try {
          tokenContent = await jwt.verify(authorization, 'A');     //如果token过期或验证失败，将抛出错误
          console.log(tokenContent)
          ctx.body = tokenContent
      } catch (err) {
          // ctx.throw(401, 'invalid token');
      } 
  }
  async post() { //no
    const ctx = this.ctx;
    const { Joi } = this.app;
    // 校验 `ctx.request.body` 是否符合我们预期的格式
    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    // const errors =  ctx.validate(createRule, this.ctx.request.body);//ok
    // console.log(errors,this.ctx.request.body)//

    // // 调用 service 创建一个 topic
    // const id = await ctx.service.topics.create(this.ctx.request.body);//ok
    // console.log(id)

    // const { Joi } = this.app;
    const j = ctx.request.body;
    console.log('接收到的传参', j)
     
    // ctx.throw(401, 'invalid token');

    const token = jwt.sign({
      user_id: 2,
      userName: ctx.request.body.username
    }, 'ABC', {
        expiresIn: '30s'//2days
    });
    // const   tokenContent = await jwt.verify(token, 'A');     //如果token过期或验证失败，将抛出错误
    //       console.log(tokenContent)
    ctx.body = {
      token: token  //随机字符串 
    };





    // console.log('>>>***********************');  //config
    // const client1 = this.app.mysql.get('db1');
    // const tt =  await client1.query('test');
    //  console.log('接收到的传参',  await ctx.service.sqlService.query('user'))


    // const id = await ctx.service.topics.create(this.ctx.request.body);//ok
    // console.log(id)

    //  const client1 =  await this.app.mysql.get('user',{userid:1});// get不传参,默认获取到第一条数据 打开在config配置中指定的库,这里的test是表 ,
    // console.log('打开数据库 test =', client1)

    // const q=client1.query('test');    
    // console.log('mysql=', q); 
 
   // const res = { test: "正常", code: 200 }
    //this.ctx.body = res || { code: 500 };
  }
  *sql(){
    const ctx = this.ctx;
      yield  ctx.service.topics.insert("44");
    const result = yield  ctx.service.topics.searcch("44"); //query查询ok insert ok delete ok
    console.log('clients=', result); 
    this.ctx.body=result; 

  }



}

module.exports = HomeController;
